package com.coinread.hr.tools.interceptor;

import com.coinread.hr.tools.bean.persistence.AdminService;
import com.coinread.hr.tools.common.JwtToken;
import com.coinread.hr.tools.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;

@Component
@Slf4j
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private AdminService adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (adminService == null) {
            BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            adminService = (AdminService) factory.getBean("adminService");
        }

        String sessionToken = CookieUtils.getCookie(request,"sessionJd");
        if (!JwtToken.verifyToken(sessionToken)) {
            toAlert(response);
            return false;
        }


        return true;
    }

    public void toAlert( HttpServletResponse response){

        try {
            response.setContentType("text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");

            OutputStreamWriter out=new OutputStreamWriter(response.getOutputStream());

            String msg="由于您长时间没有操作，session已过期，请重新登录！";
            msg=new String(msg.getBytes("UTF-8"));

            //out.write("<meta http-equiv='Content-Type' content='text/html';charset='UTF-8'/>");
            out.write("<script>");
            out.write("alert('"+msg+"');");
            out.write("top.location.href = '/index/login'; ");
            out.write("</script>");
            out.flush();
            out.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
